package com.llkj.qingnianguoxue.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.JingXuanBookTabAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.BookTabBean;
import com.llkj.qingnianguoxue.bean.MasterDetailBean;
import com.llkj.qingnianguoxue.bean.Response;
import com.llkj.qingnianguoxue.bean.response.ResponseData;
import com.llkj.qingnianguoxue.bean.response.ResponseList;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 大师详情
 */
public class MasterDetailActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_LOGIN_CODE = 6666;
    private static final int REQUEST_SUBSCRIBE_CODE = 8374;
    private ImageView ivBackground;//返回按钮,背景
    private TextView tvNameJob;//名字职位
    private TextView tvPrice, btnSubscribe;//价格，订阅\
    private FrameLayout flDescription, flVideo;//简介，视频
    private MasterDescriptionFragment descriptionFragment;//简介
//    private MasterVideoFragment videoFragment;//视频
    private String mDetailId;//详情id
    private boolean isEnable = true;
    private int isMember;
    private String masterId;

    @BindView(R.id.video_content)
    LinearLayout llVideoContent;
    @BindView(R.id.lvHorizontal)
    RecyclerView lvHorizontalView;
    private JingXuanBookTabAdapter mVideoTabAdapter;
    private List<BookTabBean> mTabData;
    private HashMap<Integer,JingXuanVideoFragment> mVideoFragmentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_master_detail);
        ButterKnife.bind(this);
        setTitle("导师详情", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, -1, -1);
//        systemBarTintManager.setStatusBarTintResource(R.color.transparent);
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        mDetailId = bundle.getString("id");

        initView();
        initListener();

        setSelection(0);

        getMasterDetail();
        getVideoClassify();
    }

    private void initView() {
        ivBackground = (ImageView) findViewById(R.id.iv_bg);

        tvNameJob = (TextView) findViewById(R.id.tv_name);//名字职位
        tvPrice = (TextView) findViewById(R.id.tv_price);//价格订阅\
        btnSubscribe = (TextView) findViewById(R.id.tv_subscribe);
        btnSubscribe.setSelected(false);
        btnSubscribe.setVisibility(View.GONE);

        flDescription = (FrameLayout) findViewById(R.id.fl_description);//简介，视频
        flVideo = (FrameLayout) findViewById(R.id.ll_video);

        mVideoFragmentList = new HashMap<>();
        lvHorizontalView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mTabData = new ArrayList<>();
        mVideoTabAdapter = new JingXuanBookTabAdapter(R.layout.item_jingxuan_books_tab,mTabData);
        mVideoTabAdapter.setType(1);
        lvHorizontalView.setAdapter(mVideoTabAdapter);

        lvHorizontalView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mVideoTabAdapter.setSelectPosition(position);
                setVideoSelection(position);
            }
        });
//        //处理沉浸式状态栏
//        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ivBack.getLayoutParams();
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
//            layoutParams.topMargin = DisplayUtil.dip2px(this, 10);
//        } else {
//            layoutParams.topMargin = statusBarHeight + DisplayUtil.dip2px(this, 10);
//        }

    }

    private void initListener() {
        btnSubscribe.setOnClickListener(this);
        flDescription.setOnClickListener(this);
        flVideo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back://返回
                finish();
                break;
            case R.id.tv_subscribe://
//                if (btnSubscribe.isSelected()) {
//                    return;
//                }
                boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                if (!isEnable) {
                    ToastUtil.makeShortText(this, "已订阅");
                    return;
                }
                if (isMember == 1) {
                    orderMaster();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mDetailId);
                    startActivityForResult(MasterSubscribeActivity.class, bundle, REQUEST_SUBSCRIBE_CODE);
                }
                break;
            case R.id.fl_description:////简介，视频
                setSelection(0);
                break;
            case R.id.ll_video://
                setSelection(1);
                break;
        }
    }

    private void orderMaster() {
        HttpMethod.orderApp(this, this, "1", masterId, "-1", "-1", "-1");
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivityForResult(LoginActivity.class, new Bundle(), REQUEST_LOGIN_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            if (REQUEST_SUBSCRIBE_CODE == requestCode) {
                btnSubscribe.setSelected(false);
                btnSubscribe.setText("已订阅");
                isEnable = false;
                setResult(RESULT_OK);
            } else if (REQUEST_LOGIN_CODE == requestCode) {
                getMasterDetail();
            }
        }
    }

    private void setSelection(int index) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragment(fragmentTransaction);
        switch (index) {
            case 0://
                setSelected(flDescription);
                llVideoContent.setVisibility(View.GONE);
                if (descriptionFragment == null) {
                    descriptionFragment = new MasterDescriptionFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("master_id", mDetailId);
                    descriptionFragment.setArguments(bundle);

                    fragmentTransaction.add(R.id.content_layout, descriptionFragment, "tab1");
                } else {
                    fragmentTransaction.show(descriptionFragment);
                }
                fragmentTransaction.commit();
                break;
            case 1://
                llVideoContent.setVisibility(View.VISIBLE);
                setSelected(flVideo);
                setVideoSelection(0);
//                if (videoFragment == null) {
//                    videoFragment = new MasterVideoFragment();
//                    Bundle bundle = new Bundle();
//                    bundle.putString("master_id", mDetailId);
//                    videoFragment.setArguments(bundle);
//
//                    fragmentTransaction.add(R.id.content_layout, videoFragment, "tab2");
//                } else {
//                    fragmentTransaction.show(videoFragment);
//                }
//
//                fragmentTransaction.commit();
                break;
        }
    }

    private void getMasterDetail() {
        HttpMethod.artistDetails(this, this, mDetailId);
    }

    private void setVideoSelection(int index) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        JingXuanVideoFragment fragment = null;
        if(mVideoFragmentList.containsKey(index)){
            fragment = mVideoFragmentList.get(index);
        }
        hideFragment(fragmentTransaction);
        if (fragment == null) {
            fragment = JingXuanVideoFragment.newInstance(index,mTabData.get(index).getId(),masterId);
            fragmentTransaction.add(R.id.content_layout, fragment, "master"+index);
            mVideoFragmentList.put(index,fragment);
        } else {
            fragmentTransaction.show(fragment);
        }
        fragmentTransaction.commit();
    }

    private void getVideoClassify(){
        HttpMethod.videoClassify(this,this);
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_ARTIST_DETAILS) {
            ResponseData<MasterDetailBean> detailBeanResponse = GsonUtil.fromJson(data,MasterDetailBean.class);
            MasterDetailBean detailBean = detailBeanResponse.getArtist();
//            ImageLoadingUtil.loadingCircleBorderImg(ivHead, detailBean.getImg(), R.color.colorffffff);
            ImageLoadingUtil.loadingUrlCenterCrop(ivBackground, detailBean.getImg());

            tvNameJob.setText(detailBean.getName()+"-"+detailBean.getPosition());
//            tvJob.setText(detailBean.getPosition());

            if (2 == detailBean.getIs_buy()) {// 是1 否 2
            } else if (1 == detailBean.getIs_buy()) {
                btnSubscribe.setText("已订阅");
                isEnable = false;
            }
            if("1".equals(detailBean.getIs_order())){
                btnSubscribe.setVisibility(View.VISIBLE);
                tvPrice.setText("￥" + detailBean.getPrice() + "银子");
            }else{
                findViewById(R.id.fl_subcribe).setVisibility(View.GONE);
            }
            isMember = detailBean.is_app;
            masterId = detailBean.getId();
        }else if (method == HttpMethod.HTTP_ORDER_ORDER_APP) {//9.4定购大师/APP
            RxBus.getInstance().post(ConstantUserInfo.REFRESH_SUBSCRIBE);
            ToastUtil.makeLongText(this, "订阅成功");
            btnSubscribe.setSelected(false);
            btnSubscribe.setText("已订阅");
            setResult(RESULT_OK);
        }else  if (method == HttpMethod.HTTP_VIDEO_CLASSIFY) {
            ResponseList<BookTabBean> responseBean  = GsonUtil.fromJsonList(data,BookTabBean.class);
            if(responseBean!=null && responseBean.getClassify()!=null){
                mTabData.clear();
                BookTabBean tabBean = null;
                for(int i=0;i<responseBean.getClassify().size();i++){
                    tabBean = responseBean.getClassify().get(i);
                    if(btnSubscribe.getVisibility()==View.GONE){//免费
                        if("订阅导师".equals(tabBean.getTilte())){
                            continue;
                        }
                    }else{//订阅
                        if("欣赏视频".equals(tabBean.getTilte())){
                            continue;
                        }
                    }
                    mTabData.add(tabBean);
                }

                mVideoTabAdapter.notifyDataSetChanged();
            }
        }
    }

    private void setSelected(View view) {
        flDescription.setSelected(false);
        flVideo.setSelected(false);
        view.setSelected(true);
    }

    /**
     * 隐藏所有的fragment
     *
     * @param transaction
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (descriptionFragment != null) {
            transaction.hide(descriptionFragment);
        }
//        if (videoFragment != null) {
//            transaction.hide(videoFragment);
//        }
        for(int i=0;i<mVideoFragmentList.size();i++){
            Fragment fragment =  mVideoFragmentList.get(i);
            if (fragment != null) {
                transaction.hide(fragment);
            }

        }
    }
}
